<template>
  <div class="notification-list">
    <a-card :bordered="false">
      <template #title>
        <span>通知中心</span>
        <a-badge :count="unreadCount" :offset="[10, 0]" />
      </template>

      <template #extra>
        <a-space>
          <a-button
            type="primary"
            :disabled="unreadCount === 0"
            @click="handleMarkAllRead"
            :loading="markAllLoading"
          >
            <CheckOutlined />
            全部已读
          </a-button>
          <a-button :icon="h(ReloadOutlined)" @click="fetchData">
            刷新
          </a-button>
        </a-space>
      </template>

      <!-- 筛选标签 -->
      <div class="filter-tabs">
        <a-radio-group
          v-model:value="activeTab"
          button-style="solid"
          @change="handleTabChange"
        >
          <a-radio-button value="all">全部</a-radio-button>
          <a-radio-button value="unread">未读</a-radio-button>
          <a-radio-button value="read">已读</a-radio-button>
        </a-radio-group>
      </div>

      <!-- 搜索表单 -->
      <div class="search-form" style="margin: 16px 0;">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="关联业务类型">
            <a-select
              v-model:value="searchForm.relatedType"
              placeholder="请选择关联业务类型"
              style="width: 220px;"
              allow-clear
            >
              <a-select-option :value="RelatedType.WORK_ORDER">工单相关</a-select-option>
              <a-select-option :value="RelatedType.MATERIAL">物料相关</a-select-option>
              <a-select-option :value="RelatedType.SYSTEM">系统通知</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearch">
                搜索
              </a-button>
              <a-button @click="resetSearch">
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 通知列表 -->
      <a-list
        :data-source="notifications"
        :loading="loading"
        item-layout="horizontal"
      >
        <template #renderItem="{ item }">
          <a-list-item
            :class="{ 'unread-item': item.isRead === 0 }"
            @click="handleItemClick(item)"
          >
            <a-list-item-meta>
              <template #title>
                <div class="notification-title">
                  {{ item.title }}
                  <a-tag
                    v-if="item.isRead === 0"
                    color="green"
                    size="small"
                    style="margin-left: 8px;"
                  >
                    未读
                  </a-tag>
                </div>
              </template>
              <template #description>
                <div>
                  <div class="notification-content">
                    {{ item.content }}
                  </div>
                  <div class="notification-meta">
                    <span class="related-info" v-if="item.relatedType">
                      {{ getRelatedTypeText(item.relatedType) }}
                    </span>
                    <span class="notification-time">
                      {{ formatDate(item.createdAt) }}
                    </span>
                    <a-button
                      v-if="item.isRead === 0"
                      type="link"
                      size="small"
                      @click.stop="handleMarkRead(item)"
                    >
                      标记已读
                    </a-button>
                  </div>
                </div>
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>

        <template #loadMore>
          <div
            v-if="hasMore"
            style="text-align: center; margin-top: 12px; height: 32px; line-height: 32px;"
          >
            <a-button @click="loadMore" :loading="loadMoreLoading">
              加载更多
            </a-button>
          </div>
        </template>
      </a-list>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, h } from 'vue'
import { message } from 'ant-design-vue'
import { useAppStore } from '@/stores/app'
import { getNotificationList, markAsRead, markAllAsRead, getUnreadCount } from '@/api/notification'
import type { Notification, NotificationQueryRequest, PageResponse, PaginationState, NotificationRelatedType } from '@/types'
import { NotificationRelatedType as RelatedType } from '@/types'
import { createPaginationFromResponse, handlePaginationNavigation } from '@/utils/pagination'
import {
  CheckOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue'

const appStore = useAppStore()

const loading = ref(false)
const loadMoreLoading = ref(false)
const markAllLoading = ref(false)
const notifications = ref<Notification[]>([])
const unreadCount = ref(0)
const activeTab = ref('all')
const hasMore = ref(true)

// 查询参数
const queryParams = reactive<NotificationQueryRequest>({
  pageSize: 10,
  current: 1,
  lastId: 0,
  isRead: undefined
})

// 搜索表单
const searchForm = reactive({
  relatedType: ''
})

// 分页状态管理
const paginationState = ref<PaginationState>({
  current: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
  hasNext: false,
  nextCursor: 0,
  previousPageCursors: []
})

// 当前页面的起始lastId
const currentPageLastId = ref(0)

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  // 一天内显示相对时间
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    if (hours < 1) {
      const minutes = Math.floor(diff / (60 * 1000))
      if (minutes < 1) {
        return '刚刚'
      }
      return `${minutes}分钟前`
    }
    return `${hours}小时前`
  }

  // 超过一天显示日期
  return date.toLocaleDateString()
}

// 获取关联类型文本
const getRelatedTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    [RelatedType.WORK_ORDER]: '工单相关',
    [RelatedType.MATERIAL]: '物料相关',
    [RelatedType.SYSTEM]: '系统通知',
  }
  return typeMap[type] || '其他通知'
}

// 获取通知列表
const fetchData = async (loadMore = false) => {
  try {
    if (loadMore) {
      loadMoreLoading.value = true
    } else {
      loading.value = true
      // 重置分页状态
      paginationState.value = {
        current: 1,
        pageSize: queryParams.pageSize || 10,
        total: 0,
        pages: 0,
        hasNext: false,
        nextCursor: 0,
        previousPageCursors: []
      }
      currentPageLastId.value = 0
      notifications.value = []
    }

    // 合并搜索参数
    const requestParams = {
      ...queryParams,
      relatedType: searchForm.relatedType || undefined,
      pageSize: paginationState.value.pageSize,
      current: paginationState.value.current,
      lastId: loadMore ? paginationState.value.nextCursor : currentPageLastId.value
    }

    const response = await getNotificationList(requestParams)
    if (response.code === 0 && response.data) {
      const pageData = response.data as PageResponse<Notification>
      const data = pageData.records || []

      if (loadMore) {
        // 加载更多时追加数据 去除重复数据
        const uniqueData = data.filter((item) => !notifications.value.some((n) => n.id === item.id))
        notifications.value = [...notifications.value, ...uniqueData]
      } else {
        notifications.value = data
      }

      // 更新分页状态
      paginationState.value = {
        current: pageData.current,
        pageSize: pageData.size,
        total: pageData.total,
        pages: pageData.pages,
        hasNext: pageData.hasNext,
        nextCursor: pageData.nextCursor,
        previousPageCursors: paginationState.value.previousPageCursors
      }

      // 更新hasMore状态
      hasMore.value = pageData.hasNext
    }
  } catch (error) {
    console.error('获取通知列表失败:', error)
  } finally {
    loading.value = false
    loadMoreLoading.value = false
  }
}

// 获取未读数量
const fetchUnreadCount = async () => {
  try {
    const response = await getUnreadCount()
    if (response.code === 0) {
      unreadCount.value = response.data
    }
  } catch (error) {
    console.error('获取未读数量失败:', error)
  }
}

// 标签切换
const handleTabChange = () => {
  switch (activeTab.value) {
    case 'unread':
      queryParams.isRead = 0
      break
    case 'read':
      queryParams.isRead = 1
      break
    default:
      queryParams.isRead = undefined
  }
  fetchData()
}

// 搜索
const handleSearch = () => {
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.relatedType = ''
  fetchData()
}

// 加载更多
const loadMore = () => {
  if (paginationState.value.hasNext) {
    // 更新分页状态为下一页
    paginationState.value.current += 1
    fetchData(true)
  }
}

// 点击通知项
const handleItemClick = (item: Notification) => {
  // 如果是未读通知，自动标记为已读
  if (item.isRead === 0) {
    handleMarkRead(item)
  }

  // 根据关联类型跳转到相应页面
  if ((item.relatedType === RelatedType.WORK_ORDER || item.relatedType === 'workorder') && item.relatedId) {
    // 跳转到工单详情页
    // router.push(`/workorder/detail/${item.relatedId}`)
  } else if ((item.relatedType === RelatedType.MATERIAL || item.relatedType === 'material') && item.relatedId) {
    // 跳转到物料详情页
    // router.push(`/material/detail/${item.relatedId}`)
  }
}

// 标记单条已读
const handleMarkRead = async (item: Notification) => {
  if (item.isRead === 1) return

  try {
    const response = await markAsRead({ id: item.id })
    if (response.code === 0) {
      // 更新本地状态
      item.isRead = 1
      unreadCount.value = Math.max(0, unreadCount.value - 1)
    }
  } catch (error) {
    console.error('标记已读失败:', error)
  }
}

// 标记全部已读
const handleMarkAllRead = async () => {
  if (unreadCount.value === 0) return

  try {
    markAllLoading.value = true
    const response = await markAllAsRead()
    if (response.code === 0) {
      message.success('已将所有通知标记为已读')
      // 更新本地状态
      notifications.value.forEach(item => {
        item.isRead = 1
      })
      unreadCount.value = 0
    }
  } catch (error) {
    console.error('标记全部已读失败:', error)
  } finally {
    markAllLoading.value = false
  }
}

onMounted(() => {
  // 设置面包屑
  appStore.setBreadcrumbs([
    { title: '首页', path: '/dashboard' },
    { title: '通知中心' }
  ])

  fetchData()
  fetchUnreadCount()
})
</script>

<style scoped>
.notification-list {
  padding: 0;
}

.filter-tabs {
  margin-bottom: 16px;
}

.unread-item {
  background-color: #f6ffed;
  border-left: 3px solid #52c41a;
}

.notification-title {
  display: flex;
  align-items: center;
  font-weight: 600;
}

.notification-content {
  color: #666;
  margin-bottom: 8px;
  line-height: 1.5;
}

.notification-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.related-info {
  font-size: 12px;
  color: #999;
}

.notification-time {
  font-size: 12px;
  color: #999;
}

:deep(.ant-list-item) {
  cursor: pointer;
  transition: background-color 0.2s;
}

:deep(.ant-list-item:hover) {
  background-color: #f5f5f5;
}
</style>
